package cn.demo.framework.config;


import cn.demo.common.core.domain.BaseEntity;
import cn.demo.common.utils.JsonUtils;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.interceptor.SimpleKey;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;


/**
 * 自定义key生成器
 */
@Configuration
public class MyCacheConfig {

    @Bean("myKeyGenerator")
    public KeyGenerator keyGenerator(){
        return (target, method, params) -> {
            if (params.length == 0) {
                return SimpleKey.EMPTY;
            }
            String sp = ".";
            StringBuilder builder = new StringBuilder();
            builder.append(method.getName()).append(sp);
            for (Object param : params) {

                // 参数为map自定义key=类名+方法名+map的key-value值
                if (param instanceof Map || param instanceof BaseEntity) {
                    // 分隔符
                    Map<String, Object> map = JsonUtils.parseMap(param);
                    if (map.isEmpty()) {
                        return builder.toString();
                    }
                    for (String key : map.keySet()) {
                        builder.append(key).append("-").append(map.get(key)).append(sp);
                    }
                }else {
                    builder.append(new SimpleKey(params));
                }
            }
            return builder.toString();
        };
    }
}
